<template>
  <van-field @click="openPicker" readonly is-link :modelValue="calcInputText" v-bind="$attrs" />
  <van-popup
    position="bottom"
    :style="{
      width: '100%',
      height: '100%',
      background: '#f2f2f2',
    }"
    v-model:show="show"
  >
    <van-nav-bar
      :title="listTitle"
      left-arrow
      right-text="确定选择"
      @click-right="confirm"
      @click-left="show = false"
    />
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ListItem
          v-for="(item, index) in list"
          @click="selectClick(index)"
          :columns="listColumns"
          :value="item"
          :key="item"
        >
          <van-icon :class="selectIndex === index ? 'act' : ''" name="success" />
        </ListItem>
      </van-list>
    </van-pull-refresh>
  </van-popup>
</template>

<script setup lang="ts">
  import { ref, computed, unref } from "vue";
  import { ListItem } from "/@/components/ListItem";
  import { ItemColumn } from "/@/utils/helper/typing";
  import { showToast } from "vant";

  const props = withDefaults(
    defineProps<{
      api: (...arg: any) => Promise<any>;
      listColumns: ItemColumn[];
      // 表单提交使用字段
      useField: string;
      // 表单字段名
      showField: string;
      formValue: any;
      modelValue?: string;
      isView?: true;
      listTitle?: string;
      afterFetch?: (...arg: any) => any;
    }>(),
    {
      listTitle: "实体列表",
    },
  );
  const list = ref<any[]>([]);
  const selectIndex = ref(-1);
  const show = ref(false);

  const loading = ref(false);
  const finished = ref(false);
  const refreshing = ref(false);
  const page = ref(1);
  const calcInputText = computed(() => {
    if (unref(selectIndex) !== -1) {
      return unref(list)[unref(selectIndex)][props.showField];
    } else {
      return props.formValue[props.showField];
    }
  });

  const emits = defineEmits<{
    (e: "change", record: any): void;
    (e: "update:modelValue", fieldValue: any): void;
  }>();

  const openPicker = () => {
    if (props.isView) {
      showToast("表单查看状态");
    } else {
      show.value = true;
    }
  };
  const onLoad = async () => {
    const { items, total } = await props.api({
      page: page.value,
      pageSize: 10,
    });
    if (props.afterFetch) {
      // 请求后处理
      props.afterFetch(items).forEach((resItem) => {
        // 判重复
        if (
          unref(list).findIndex((item) => JSON.stringify(item) === JSON.stringify(resItem)) === -1
        ) {
          list.value.push(resItem);
        }
      });
    } else {
      items.forEach((resItem) => {
        if (
          unref(list).findIndex((item) => JSON.stringify(item) === JSON.stringify(resItem)) === -1
        ) {
          list.value.push(resItem);
        }
      });
    }
    loading.value = false;
    refreshing.value = false;
    if (unref(list).length >= total) {
      finished.value = true;
    } else {
      finished.value = false;
      page.value++;
    }
  };

  /**
   * 下拉刷新
   */
  async function onRefresh() {
    refreshing.value = true;
    finished.value = true;
    loading.value = true;
    page.value = 1;
    list.value = [];
    await onLoad();
  }

  const selectClick = (index: number) => {
    selectIndex.value = index;
  };

  const confirm = () => {
    //实体组件change事件
    emits("change", unref(list)[unref(selectIndex)]);
    emits("update:modelValue", unref(list)[unref(selectIndex)]?.[props.useField]);
    show.value = false;
  };
</script>

<style lang="less" scoped>
  /deep/ .van-list {
    .list-item {
      position: relative;
      .van-icon {
        position: absolute;
        right: 1rem;
        top: 1rem;
        display: none;
        font-size: 2rem;
        color: #3c8aff;
      }
    }
    .van-icon.act {
      display: block;
    }
  }
</style>
